import "@/app/global.css";

import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider,
} from "@react-navigation/native";
import * as SplashScreen from "expo-splash-screen";
import { useFonts } from "expo-font";
import { Stack } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { useEffect } from "react";
import "react-native-reanimated";
import { Provider, useSelector } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { GluestackUIProvider, ToastContainer } from "gluestack-ui";
import { RootState, store, persistor } from "@/stores";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { RouteGuard } from "@/components/auth/RouteGuard";
import { ThemeToggleButton } from "@/components/ThemeToggleButton";
import "@/i18ns";

SplashScreen.preventAutoHideAsync();

function AppContent() {
  const theme = useSelector((state: RootState) => state.theme.theme);

  const [loaded] = useFonts({
    "Roboto-Bold": require("../assets/fonts/Roboto-Bold.ttf"),
    "NotoSans-Thai": require("../assets/fonts/NotoSansThai.ttf"),
    "Roboto-Medium": require("../assets/fonts/Roboto-Medium.ttf"),
    "DIN-Bold": require("../assets/fonts/DIN-Bold.otf"),
    Roboto: require("../assets/fonts/Roboto-Regular.ttf"),
  });

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return (
    <GluestackUIProvider mode={theme}>
      <ThemeProvider value={theme === "dark" ? DarkTheme : DefaultTheme}>
        <ToastContainer />
        <RouteGuard>
          <Stack screenOptions={{ headerShown: false }}>
            <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
            <Stack.Screen name="+not-found" />
          </Stack>
          <StatusBar style={theme === "dark" ? "light" : "dark"} />
          <ThemeToggleButton />
        </RouteGuard>
      </ThemeProvider>
    </GluestackUIProvider>
  );
}

export default function RootLayout() {
  return (
    <ErrorBoundary>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <AppContent />
        </PersistGate>
      </Provider>
    </ErrorBoundary>
  );
}
